var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    role: 'admin',
    outsideUser: false,
    img_semitrailer_licence:'/images/vehiclelicense.jpg',
    progress: 0,
    totalBytesSent: 0,
    totalBytesExpectedToSend: 0,
    formType : 'add'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadData();
    this.setData({
      is_fleet:app.globalData.role_default == 'fleet'?true:false
    })
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  search: function () {
    this.loadData();
  },
  loadData: function () {
    var that = this;
    util.getData("/atapi/vehicle/vehicle/semitrailer", {
      'CO_ID': app.globalData.CO_ID,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var count = res.data.data[1][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        that.setData({
          dataList: res.data.data[0],
          count: count,
          pageNumber: pageNumber,
          page: that.data.page == 0 ? 1 : that.data.page
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          dataList: [],
          user_id:app.globalData.user_id,
          is_fleet:app.globalData.role_default == 'fleet'?true:false,
        });
      }
    });
  },
  deleteData:function(){
    var that = this;
    var _currentData = that.data._currentData;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除吗？',
      success (res) {
        if (res.confirm) {
            util.deleteData("/atapi/vehicle/vehicle/semitrailer", {
              id: _currentData.ID,
              user_id:app.globalData.user_id,
              CO_ID:app.globalData.CO_ID,
              truename:app.globalData.truename,
              logs:that.data.plate+','+_currentData.name+','+_currentData.site+','+_currentData.fee+','+_currentData.upkeep_time+','+app.globalData.user_id
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function(){
                      that.hideModal();
                        that.loadData();
                    },3000)
                  }
                });
              }
            });
          }
        }
        })
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: e.currentTarget.dataset.title,
      modalType:e.currentTarget.dataset.type
    })
    if(e.currentTarget.dataset.type == 'detail'){
       var id = e.currentTarget.id;
       var dataList = that.data.dataList;
       for(var i=0;i<dataList.length;i++){
         if(dataList[i].ID == id){
           var currentData = [];
           currentData.push({name:'号牌号码',value:dataList[i].plate});
           currentData.push({name:'车辆类型',value:dataList[i].vehicle_type});
           currentData.push({name:'所有人',value:dataList[i].owner});
           currentData.push({name:'住址',value:dataList[i].address});
           currentData.push({name:'使用性质',value:dataList[i].use_character});
           currentData.push({name:'品牌型号',value:dataList[i].model});
           currentData.push({name:'识别代号',value:dataList[i].vin});
           currentData.push({name:'发动机号',value:dataList[i].engine_no});
           currentData.push({name:'注册日期',value:dataList[i].register_date});
           currentData.push({name:'发证日期',value:dataList[i].issue_date});
           currentData.push({name:'发证机构',value:dataList[i].issued_by});
           currentData.push({name:'行驶证',value:dataList[i].photo});
            that.setData({
              _currentData:dataList[i],
               currentData:currentData
            })
         }
         util.getData("/atapi/vehicle/vehicle/semitrailerBindVehicleLogs", {
          'semitrailer': id
        }, function (res, error) {
          console.log(res); console.log(error)
          if (res.data.success) {
            that.setData({
              semitrailerBindVehicleLogs: res.data.data
            });
          }else{
            that.setData({
              semitrailerBindVehicleLogs: []
            });
          }
        });
       }
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  cannelUpload:function(){
    this.setData({
      uploading: false
    })
  },
  chooseImage: function (e) {
    var that = this;
    // if(that.data.plate  == ''){
    //   wx.showToast({
    //     title: "请先填写车牌",
    //     image: '/images/wrong.png',
    //     duration: 2000
    //   });
    //   return false;
    // }
    wx.chooseImage({
      sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // wx.showLoading({
        //   title: '上传中...',
        //   mask:true
        // })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var item = String(e.currentTarget.id), item_value = {};
        item_value[item] = res.tempFilePaths[0];
        that.setData(item_value);
        that.setData({
          uploading: true,
          progress: 0,
          totalBytesSent: 0,
          totalBytesExpectedToSend: 0
        })
        that.uploadTask = wx.uploadFile({
          url: app.server + '/wechat/passport/uploadCard_vehicle',
          header:{
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'CO_ID': app.globalData.CO_ID,
            'user_id': app.globalData.user_id,
            'item': item,
            'driverId': app.globalData.driverId,
            'plate': that.data.plate
          },
          success: function (res) {
            var data = JSON.parse(res.data);
            console.log(data)
            if (data.success) {
              var upload_item = String(e.currentTarget.id), item_value = {};
              item_value[upload_item] = app.server + data.data[0].path;
              that.setData(item_value);
              if (data.licence){
                that.setData(data.licence)
                that.setData({
                  plate:data.licence.plate_no
                })
              }
            }else{
              wx.showModal({
                title: '温馨提示',
                content: data.data,
                success: function (res) {
                }
              });
            }
          },
          complete: function () {
            that.setData({
              uploading: false
            })
          }
        })
        that.uploadTask.onProgressUpdate((res) => {
          that.setData({
            progress: res.progress,
            totalBytesSent: Number(res.totalBytesSent / 1000 / 1000).toFixed(3),
            totalBytesExpectedToSend: Number(res.totalBytesExpectedToSend / 1000 / 1000).toFixed(3)
          })
        })
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.url] // 需要预览的图片http链接列表
    })
  },
  //提交表单
  saveFormData: function () {
    var that = this;

    var formData = {};

    formData.plate = that.data.plate||'';
    formData.vehicle_type = that.data.vehicle_type||'';
    formData.owner = that.data.owner||'';
    formData.address = that.data.address||'';
    formData.use_character = that.data.use_character||'';
    formData.model = that.data.model||'';
    formData.vin = that.data.vin||'';
    formData.engine_no = that.data.engine_no||'';
    formData.register_date = that.data.register_date||'';
    formData.issue_date = that.data.issue_date||'';
    formData.side = that.data.side||'';
    formData.issued_by = that.data.issued_by||'';
    formData.photo = that.data.img_semitrailer_licence;
    console.log(formData)
    if (formData.photo == '' ||formData.photo == '/images/vehiclelicense.jpg' ) {
      wx.showToast({
        title: "请上传行驶证",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.plate == '') {
      wx.showToast({
        title: "请填写车牌",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.vehicle_type == '') {
      wx.showToast({
        title: "请填写车辆类型",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.vin == '') {
      wx.showToast({
        title: "请填写识别号",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    formData.CO_ID = app.globalData.CO_ID;
    formData.ADD_USER = app.globalData.user_id;
    if (that.data.formType == 'add'){
      util.postData("/atapi/vehicle/vehicle/semitrailer", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }else{
      formData.id = that.data.ID;
      util.putData("/atapi/vehicle/vehicle/semitrailer", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "编辑成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "编辑失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})